<template>
	<view class="w-100 h-100 overflow-hidden">
		<view @click="show">设置</view>
		<view class="content">
			<canvas canvas-id="clockCanvas" id="clockCanvas" type="2d" class="clock-canvas"
				@touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"
				style="z-index: 0;"></canvas>
			<view class="time-display flex">
				<view @click="keyboardShow('hour')"> {{ formatTime(currentTime.hour) }} </view>
				<view class="pl-1 pr-1">:</view>
				<view @click="keyboardShow('minute')"> {{ formatTime(currentTime.minute) }} </view>
			</view>
		</view>
		<!-- 弹窗 -->
		<uni-popup ref="popupRef" type="bottom" borderRadius="10px 10px 0 0" background-color="#fff">
			<view class="pb-5">
				<view class="w_92 m-auto">
					<view class="flex align-center justify-between pt-4">
						<view class="font-md-g font-weight-bold text-1D1C1C">时钟设置</view>
						<image src="@/static/close.png" style="width: 40rpx;height: 40rpx;" @click="close"></image>
					</view>
					<view class="flex align-center justify-between mt-6">
						<view class="font">表盘样式</view>
						<view class="flex settings">
							<view class="rounded-circle border-box flex align-center justify-center font-base mr-3"
								:class="[dialPlateType== 0 ? 'active' : '']" @click="setDialPlateType(0)">
								刻度 + 数字</view>
							<view class="rounded-circle border-box flex align-center justify-center font-base mr-3"
								:class="[dialPlateType== 1 ? 'active' : '']" @click="setDialPlateType(1)">仅刻度
							</view>
							<view class="rounded-circle border-box flex align-center justify-center font-base"
								:class="[dialPlateType== 2 ? 'active' : '']" @click="setDialPlateType(2)">仅数字
							</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<m-keyboard ref="keyboardRef" @keyboardChange="keyboardChange"></m-keyboard>
	</view>
</template>

<script setup name="clockIndex">
	import {
		ref,
		onMounted,
		getCurrentInstance
	} from "vue";
	const popupRef = ref(null);
	const keyboardRef = ref(null);
	const instance = getCurrentInstance()
	let ctx, canvas, activeHand, keyboardType
	let lastAngle = 0
	const currentTime = ref({
		hour: 0,
		minute: 0
	})
	let centerX = 150
	let centerY = 150
	let radius = 140

	const dialPlateType = ref(uni.getStorageSync('dialPlateType') || 0)

	const initClock = () => {
		const query = uni.createSelectorQuery().in(instance);
		query.select('#clockCanvas')
			.fields({
				node: true,
				size: true
			})
			.exec(res => {
				const canvasNode = res[0].node;
				const ctxNode = canvasNode.getContext('2d');
				const dpr = uni.getSystemInfoSync().pixelRatio;

				canvasNode.width = 300 * dpr;
				canvasNode.height = 300 * dpr;
				ctxNode.scale(dpr, dpr);
				ctx = ctxNode;
				if (dialPlateType.value == 0) {
					drawClock(true, true)
				}
				if (dialPlateType.value == 1) {
					drawClock(true, false)
				}
				if (dialPlateType.value == 2) {
					drawClock(false, true)
				}
			});
	}
	onMounted(() => {
		initClock()
	})
	const setDialPlateType = (type) => {
		dialPlateType.value = type
		uni.setStorageSync('dialPlateType', type)
		if (type == 0) {
			drawClock(true, true)
		}
		if (type == 1) {
			drawClock(true, false)
		}
		if (type == 2) {
			drawClock(false, true)
		}
	}
	const drawClock = (isDrawScale = true, isDrawNum = true) => {
		ctx.clearRect(0, 0, 300, 300);

		// 绘制表盘
		ctx.beginPath();
		ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
		ctx.strokeStyle = '#333';
		ctx.lineWidth = 4;
		ctx.stroke();

		// 绘制刻度
		if (isDrawScale) {
			for (let i = 0; i < 12; i++) {
				const angle = (i * 30) * Math.PI / 180;
				const length = i % 3 === 0 ? 20 : 10;
				ctx.beginPath();
				ctx.moveTo(
					centerX + Math.sin(angle) * (radius - length),
					centerY - Math.cos(angle) * (radius - length)
				);
				ctx.lineTo(
					centerX + Math.sin(angle) * radius,
					centerY - Math.cos(angle) * radius
				);
				ctx.strokeStyle = '#333';
				ctx.lineWidth = i % 3 === 0 ? 4 : 2;
				ctx.stroke();
			}
		}
		// 绘制数字（新增部分）
		if (isDrawNum) {
			ctx.fillStyle = '#333';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			ctx.font = '16px Arial';

			for (let i = 0; i < 12; i++) {
				const angle = (i * 30) * Math.PI / 180;
				const textRadius = radius - ((isDrawScale == false && isDrawNum == true) ? 15 : 30); // 数字距离中心的距离

				// 计算数字位置
				const x = centerX + Math.sin(angle) * textRadius;
				const y = centerY - Math.cos(angle) * textRadius;

				// 处理12点位置的数字显示
				const number = i === 0 ? 12 : i;
				ctx.fillText(number.toString(), x, y);
			}
		}
		// 绘制指针
		drawHand(currentTime.value.minute * 6, 80, 4, '#666'); // 分针
		drawHand(currentTime.value.hour * 30 + currentTime.value.minute * 0.5, 50, 6, '#333'); // 时针
	}
	const drawHand = (angle, length, width, color) => {
		const radian = (angle - 90) * Math.PI / 180;

		ctx.save();
		ctx.beginPath();
		ctx.moveTo(centerX, centerY);
		ctx.lineTo(
			centerX + Math.cos(radian) * length,
			centerY + Math.sin(radian) * length
		);
		ctx.strokeStyle = color;
		ctx.lineWidth = width;
		ctx.lineCap = 'round';
		ctx.stroke();
		ctx.restore();
	}
	const handleTouchStart = (e) => {
		const touch = e.touches[0];
		detectActiveHand(touch.x, touch.y);
	}
	const handleTouchMove = (e) => {
		if (!activeHand) return;
		const touch = e.touches[0];
		updateTime(touch.x, touch.y);
	}
	const handleTouchEnd = () => {
		activeHand = null;
	}
	const detectActiveHand = (x, y) => {
		const dx = x - centerX;
		const dy = y - centerY;
		const distance = Math.sqrt(dx * dx + dy * dy);

		if (distance < radius) {
			activeHand = distance < 80 ? 'hour' : 'minute';
			updateTime(x, y);
		}
	}
	const updateTime = (x, y) => {
		const dx = x - centerX;
		const dy = y - centerY;
		let angle = Math.atan2(dy, dx) * 180 / Math.PI + 90;
		if (angle < 0) angle += 360;

		if (activeHand === 'hour') {
			currentTime.value.hour = Math.floor(angle / 30) % 12;
			currentTime.value.minute = Math.round((angle % 30) * 2);
		} else if (activeHand === 'minute') {
			currentTime.value.minute = Math.round(angle / 6) % 60;
			if (lastAngle - angle > 310) {
				if (currentTime.value.hour != 11) {
					currentTime.value.hour += 1
				} else {
					currentTime.value.hour = 0
				}
			}
			if (lastAngle - angle < -310) {
				if (currentTime.value.hour != 0) {
					currentTime.value.hour -= 1
				} else {
					currentTime.value.hour = 11
				}
			}
			lastAngle = angle
		}

		if (dialPlateType.value == 0) {
			drawClock(true, true)
		}
		if (dialPlateType.value == 1) {
			drawClock(true, false)
		}
		if (dialPlateType.value == 2) {
			drawClock(false, true)
		}
	}
	const formatTime = (num) => {
		return num.toString().padStart(2, '0');
	}
	const show = () => {
		popupRef.value.open()
	}
	const close = () => {
		popupRef.value.close()
	}
	const keyboardShow = (e) => {
		keyboardRef.value.show()
		keyboardType = e
	}
	const keyboardChange = (e) => {
		if (keyboardType === 'hour') {
			const hourLength = (currentTime.value.hour + '').length
			if (currentTime.value.hour == 0) {
				if (e === 'del') {
					return
				}
				currentTime.value.hour = e
			} else {
				if (hourLength == 1) {
					if (e === 'del') {
						currentTime.value.hour = 0
					} else {
						const hour = currentTime.value.hour + '' + e
						if (hour <= 11) {
							currentTime.value.hour = hour - 0
						} else {
							uni.showToast({
								icon: "none",
								title: '时针的最大刻度值为11'
							})
							currentTime.value.hour = 11
						}
					}
				} else {
					if (e === 'del') {
						currentTime.value.hour = (currentTime.value.hour + '')[0] - 0
					} else {
						uni.showToast({
							icon: "none",
							title: '时针的最大刻度值为11'
						})
						currentTime.value.hour = 11
					}
				}
			}
		}
		if (keyboardType === 'minute') {
			const minuteLength = (currentTime.value.minute + '').length
			if (currentTime.value.minute == 0) {
				if (e === 'del') {
					return
				}
				currentTime.value.minute = e
			} else {
				if (minuteLength == 1) {
					if (e === 'del') {
						currentTime.value.minute = 0
					} else {
						const minute = currentTime.value.minute + '' + e
						if (minute <= minute) {
							currentTime.value.minute = minute - 0
						} else {
							uni.showToast({
								icon: "none",
								title: '分针的最大刻度值为59'
							})
							currentTime.value.minute = 59
						}
					}
				} else {
					if (e === 'del') {
						currentTime.value.minute = (currentTime.value.minute + '')[0] - 0
					} else {
						uni.showToast({
							icon: "none",
							title: '分针的最大刻度值为59'
						})
						currentTime.value.minute = 59
					}
				}
			}
		}
		if (dialPlateType.value == 0) {
			drawClock(true, true)
		}
		if (dialPlateType.value == 1) {
			drawClock(true, false)
		}
		if (dialPlateType.value == 2) {
			drawClock(false, true)
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
	}

	.clock-canvas {
		width: 300px;
		height: 300px;
		margin: 20px;
	}

	.time-display {
		font-size: 24px;
		font-weight: bold;
		margin-top: 20px;
	}

	.settings view {
		min-width: 110rpx;
		padding: 0 20rpx;
		height: 60rpx;
		border: 1px solid #E5E5E5;
	}

	.active {
		background: linear-gradient(180deg, #C4A8FF 0%, #A176F6 100%);
		border: 0 !important;
		color: #F9F9F9;
	}

	.confirm {
		margin-top: 156rpx;
		background: linear-gradient(180deg, #C4A8FF 0%, #A176F6 100%);
		height: 100rpx;
	}
</style>